package com.njupt.user.webapp.action;

import java.util.Date;
import java.util.Properties;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.njupt.service.BaseAction;
import com.njupt.system.model.UserAuthority;
import com.njupt.user.model.User;
import com.opensymphony.xwork2.Preparable;
@ParentPackage(value="user")
@Results({ 
	@Result(name = "success", location = "/registerSuccess.jsp"),
	@Result(name = "failure", location = "/register.jsp"),
	@Result(name = "login", location = "/login.jsp")
	})
public class RegisterAction extends BaseAction implements Preparable
{
	private User user;
	private String msg;
	@Override
	public void prepare() throws Exception
	{
		Long userId = (Long) this.getParameter("user.id", Long.class);
		if(userId!=null){
			user = (User) manager.get(User.class, userId);
		}
	}
	public String register() throws MessagingException{
		String certCode = (String) this.getParameter("verifyCode", String.class);
		String[] authorities = new String[]{"customer"};
		String email = (String) this.getParameter("user.username", String.class);
		String identity = (String) this.getParameter("userAuthority.authority", String.class);
		if(certCode.toLowerCase().equals(this.getSession().getAttribute("certCode2").toString().toLowerCase())){
			user.setEnabled(false);
			user.setAuthorities(authorities);
			user.setEmail(email);
			user = (User) manager.save(user);
			UserAuthority userAuthority = new UserAuthority();
			userAuthority.setUserId(user.getId());
			userAuthority.setUsername(user.getUsername());
			userAuthority.setAuthority(identity);
			userAuthority = (UserAuthority) manager.save(userAuthority);
			return sendMail(user);
		}else{
			msg = "验证码错误";
			return "failure";
		}
		
	}
	public String active(){
		user.setEnabled(true);
		user.setRegTime(new Date());
		manager.save(user);
		return "login";
	}
	public String sendAgain() throws MessagingException{
		return sendMail(user);
	}
	public String sendMail(User user) throws MessagingException{
		UserAuthority userAuthority = manager.findUniqueBy(UserAuthority.class, "userId", user.getId());
		String content = "<strong>--欢迎您注册南邮博客系统--</strong><br/>" +
				"请点击激活你的账号:&gt;&gt;<a href='http://localhost:8080/ny_blog/user/register.action?method:active&user.id="+
				user.getId()+"'>激活</a>";
		String title = "南邮博客系统."; 
		Properties props = new Properties();
		props.put("mail.smtp.host", "smtp.163.com");//存储发送邮件的服务器的信息
		props.put("mail.smtp.auth", "true"); //同时通过验证
		Session s = Session.getInstance(props);//根据属性新建一个邮件会话
		MimeMessage message = new MimeMessage(s); //邮件会话新建一个消息对象
		//设置邮件
		InternetAddress from = new InternetAddress("njupt_zhandui@163.com");
		message.setFrom(from);//设置发件人
		message.setSubject(title);   //发送邮件的标题
		message.setSentDate(new Date());
		s.setDebug(true);
		Multipart mm = new MimeMultipart();//新建一个MimeMultipart对象用来存放BodyPart对象
		BodyPart mdp = new MimeBodyPart();//新建一个存放信件内容的BodyPart对象
		InternetAddress to = null;
		if("manager".equals(userAuthority.getAuthority())){
			to = new InternetAddress("781954358@qq.com");
		}else{
			to = new InternetAddress(user.getEmail());
		}
		//设置发件人，并设置其接受类型为To
		message.setRecipient(Message.RecipientType.TO, to);
		mdp.setContent(content, "text/html;charset=GBK");
		mm.addBodyPart(mdp);//附件
		message.setContent(mm);
		message.saveChanges();      //存储邮件信息
		Transport transport = s.getTransport("smtp");
		//以stmp方式登录邮箱，第一个参数是发送邮件用的服务器SMTP地址，第二参数为用户名，第三个参数密码
		transport.connect("smtp.163.com", "njupt_zhandui@163.com", "njupt123456789");
		//发送邮件，其中第二个参数是所有已设好的收件人地址
		transport.sendMessage(message, message.getAllRecipients());
		transport.close();
		return "success";
	}
	public User getUser()
	{
		return user;
	}
	public void setUser(User user)
	{
		this.user = user;
	}
	public String getMsg()
	{
		return msg;
	}
	public void setMsg(String msg)
	{
		this.msg = msg;
	}
}
